package com.jianganming.nio.reactor;

import org.springframework.util.StringUtils;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

//处理客户端发送的消息
public class Handler implements Runnable{
    private SocketChannel channel;
    public Handler(SocketChannel channel) {
        this.channel = channel;
    }

    //读取客户端的消息
    @Override
    public void run() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int len = 0,total=0;
        String msg = "";
        try{
            do{
                len = channel.read(buffer);//将消息读入缓冲区
                if(len>0){
                    total += len;
                    msg += new String(buffer.array(),0,total);
                }
            }while (len>buffer.capacity());
            if(!StringUtils.isEmpty(msg))
                System.out.println(channel.getRemoteAddress()+":"+msg);
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }
}
